package com.xwtech.cring.admin.controller;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.xwtech.cms.data.AbstractDataAdapter;
import com.xwtech.cms.data.db.JdbcTransaction;
import com.xwtech.cring.admin.pub.AdminUserRetConst;
import com.xwtech.framework.pub.result.ResultInfo;
import com.xwtech.framework.pub.result.ResultInfos;
import com.xwtech.framework.pub.utils.DateUtils;
import com.xwtech.framework.pub.utils.StringUtils;
import com.xwtech.framework.pub.web.RequestNameConstants;

public class AdminUserController extends MultiActionController {

	private static final Log log = LogFactory.getLog(AdminUserController.class);

	private HashMap updateDBfromXml(HttpServletRequest request, String query)
			throws SQLException {
		HashMap map = new HashMap();
		ResultInfos resultInfos = new ResultInfos();
		map.put(RequestNameConstants.RESULTINFOS, resultInfos);
		String adapter = request.getParameter("_adapter");
		String url = request.getParameter("_url");
		String success = request.getParameter("_success");
		String failure = request.getParameter("_failure");

		// 对得到的xml路径字符串分组
		String[] xmlString = query.split(",");
		AbstractDataAdapter ada = AbstractDataAdapter.getDataAdapter(request
				.getSession().getServletContext(), adapter);
		int ret = -1;
		log.debug("共有sql-xml配置文件" + xmlString.length + "个");
		if (xmlString.length > 1) {
			log.debug("需要进行事务处理...");
			JdbcTransaction transaction = ada.getTransaction();
			try {
				for (int i = 0; i < xmlString.length; i++) {
					ret = transaction.update(xmlString[i], request);
				}
				transaction.commit();
			} catch (Exception e) {
				log.error("数据库操作时出错！", e);
				transaction.rollback();
				ret = -1;
			}
		} else {
			ret = ada.update(query, request);
		}
		if (ret < 0) {
			resultInfos.add(new ResultInfo(Integer.parseInt(failure)));
			log.debug("数据库操作失败...");
		} else {
			resultInfos.add(new ResultInfo(Integer.parseInt(success)));
			log.debug("数据库操作成功...");
		}
		resultInfos.setGotoUrl(url);
		return map;
	}

	private HashMap checkUserExist(HttpServletRequest request) {
		String query = request.getParameter("checkQuery");
		String url = request.getParameter("_url");
		AbstractDataAdapter ada = AbstractDataAdapter.getDataAdapter(request
				.getSession().getServletContext(), null);
		List list = ada.list(query, request);
		HashMap map = null;
		if (list != null && list.size() > 0) { // 用户已经存在
			log.debug("该用户已存在，返回提示信息...");
			map = new HashMap();
			ResultInfos resultInfos = new ResultInfos();
			map.put(RequestNameConstants.RESULTINFOS, resultInfos);
			resultInfos.add(new ResultInfo(301002));
			resultInfos.setGotoUrl(url);
		}
		return map;
	}

	public ModelAndView addUser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// 给密码MD5加密
		request.setAttribute("password", StringUtils.hashKey("66666666", "MD5"));
		// 插入sys_user_info表时，若没有填入用户姓名，则
		String username = request.getParameter("user_name");
		if (username == null || username.trim().equals("")) {
			username = request.getParameter("login_name");
		}
		request.setAttribute("tmp_name", username);
		// 插入sys_user_info表用户创建时间
		request.setAttribute("begin_time", DateUtils.getChar14());
		// 把多个SQL xml文件放在事务中执行保持一致性
		HashMap map = null;
		// 判断用户是否存在
		map = this.checkUserExist(request);
		if (map == null) {
			log.debug("该用户在数据库中不存在");
			// 判断新增用户时是否选择了用户组
			String query = null;
			String roleId = request.getParameter("role_id");
			if( roleId.equals("")|| roleId==null) {   // 用户选择了默认的"------",即没选择用户组
				log.debug("没选择用户组...");
				query = "/admin/insertFrameLogin.xml,/admin/insertSysUserInfo.xml";
			} else {
				query = "/admin/insertFrameLogin.xml,/admin/insertSysUserInfo.xml,/admin/insertSysUserRole.xml";
			}
			map = updateDBfromXml(request,query);   
		}
		return new ModelAndView("/cring/jsp/admin/information.jsp",
				RequestNameConstants.INFORMATION, map);
	}
	
	public ModelAndView addUserGroup(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String query = "/admin/insertSysRole.xml";
		HashMap map = updateDBfromXml(request,query);
		return new ModelAndView("/cring/jsp/admin/information.jsp",
				RequestNameConstants.INFORMATION, map);
	}
	
	public ModelAndView editGroup(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String query = request.getParameter("editQuery");
		HashMap map = updateDBfromXml(request,query);
		return new ModelAndView("/cring/jsp/admin/information.jsp",
				RequestNameConstants.INFORMATION, map);
	}
	
	public ModelAndView delGroup(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String query = request.getParameter("delQuery");
		HashMap map = updateDBfromXml(request,query);
		return new ModelAndView("/cring/jsp/admin/information.jsp",
				RequestNameConstants.INFORMATION, map);
	}
	
	public ModelAndView initPassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HashMap map = new HashMap();
		ResultInfos resultInfos = new ResultInfos();
		map.put(RequestNameConstants.RESULTINFOS, resultInfos);
		
		String query = "/admin/updateframeLogin4Password.xml";
		request.setAttribute("password", StringUtils.hashKey("66666666", "MD5"));
		
		AbstractDataAdapter ada = AbstractDataAdapter.getDataAdapter(request
				.getSession().getServletContext(), null);
		int ret = -1;
		ret = ada.update(query, request);
		if (ret < 0) {
			resultInfos.add(new ResultInfo(AdminUserRetConst.USER_PASSWORD_INIT_SUCCESS));
			log.debug("数据库操作失败...");
		} else {
			resultInfos.add(new ResultInfo(AdminUserRetConst.USER_PASSWORD_INIT_SUCCESS));
			log.debug("数据库操作成功...");
		}
		return new ModelAndView("/cring/jsp/admin/information.jsp",
				RequestNameConstants.INFORMATION, map);
	}
}
